package org.hhf.rpt.exception;

import lombok.extern.slf4j.Slf4j;
import org.hhf.rpt.controller.ResponseResult;
import org.hhf.rpt.controller.ResponseStatus;
import org.hhf.rpt.domain.I18n;
import org.hhf.rpt.service.I18nService;
import org.hhf.rpt.util.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.MessageFormat;
import java.util.Locale;

@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

	@Resource
	private I18nService i18nService;

	/**
	 * 处理自定义的业务异常
	 * @param req
	 * @param e
	 * @return
	 */
	@ExceptionHandler(value = BizException.class)
	@ResponseBody
	public ResponseResult bizExceptionHandler(HttpServletRequest req, BizException e){
		log.error("发生业务异常！原因是：{}",e.getErrorMsg());
		String errorCode = e.getErrorCode();
		String errorMsg = e.getErrorMsg();
		Object[] msgParams = e.getMsgParams();
		if (StringUtils.isNotBlank(errorCode)) {
			I18n i18n = i18nService.getDefaultMsg(errorCode);
			if (i18n!= null) {
				errorMsg = i18n.getMsg();
				if (msgParams != null) {
					String[] language = i18n.getLocale().split("_");
					Locale locale = new Locale(language[0],language[1]);
					errorMsg = new MessageFormat(errorMsg, locale).format(msgParams);
				}
			}
		}
		return ResponseResult.failure(errorCode, errorMsg);
	}

	/**
	 * 处理自定义的业务异常
	 * @param req
	 * @param e
	 * @return
	 */
    @ExceptionHandler(value = RuntimeException.class)
    @ResponseBody
	public  ResponseResult runtimeExceptionHandler(HttpServletRequest req, RuntimeException e){
    	log.error("发生业务异常！原因是：{}",e.getMessage());
    	return ResponseResult.failure(ResponseStatus.INTERNAL_SERVER_ERROR.getCode(),e.getMessage());
    }

	/**
	 * 处理空指针的异常
	 * @param req
	 * @param e
	 * @return
	 */
	@ExceptionHandler(value =NullPointerException.class)
	@ResponseBody
	public ResponseResult exceptionHandler(HttpServletRequest req, NullPointerException e){
		log.error("发生空指针异常！原因是:",e);
		return ResponseResult.failure(ResponseStatus.BAD_REQUEST.getCode(), e.getMessage());
	}


    /**
     * 处理其他异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value =Exception.class)
	@ResponseBody
	public ResponseResult exceptionHandler(HttpServletRequest req, Exception e){
    	log.error("未知异常！原因是:",e);
       	return ResponseResult.failure(ResponseStatus.INTERNAL_SERVER_ERROR.getCode(), e.getMessage());
    }
}